﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Services;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using Library.Logging;
using NguyenHoa.Domains;

namespace NguyenHoa.Web.Admin
{
  public partial class NewsCategoryPage : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;
    

    internal override int RequiredPermission
    {
      get
      {
        switch (NewsType)
        {
          case NewsCategoryType.Normal:
            return (int)FunctionList.AdNews;
          //case NewsCategoryType.Promotion:
          //  return (int)FunctionList.Promotion;
        }
        return (int)FunctionList.AdNews;
      }
    }

    private string NewsType
    {
      get
      {
        string newsType = string.Empty;
        if (Request.QueryString["t"] != null)
          newsType = Request.QueryString["t"].ToString().ToUpper();
        if (newsType != NewsCategoryType.Normal && newsType != NewsCategoryType.Promotion)
          return string.Empty;
        return newsType;
      }
    }

    #endregion

    #region Method

    private void InitPage()
    {
      if (String.IsNullOrEmpty(NewsType))
        Response.Redirect("NewsCategory.aspx?t=" + NewsCategoryType.Normal);
    }

    private void LoadCategory()
    {
      TList<NewsCategory> ds = new NewsCategoryService().Find("Type=" + NewsType);

      gvCategory.DataSource = ds;
      gvCategory.DataBind();
    }

    private string DeleteCategory(int Id)
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          NewsCategoryLocaleService categoryLocaleService = new NewsCategoryLocaleService();
          TList<NewsCategoryLocale> listCategoryLocale = categoryLocaleService.GetByNewsCategoryId(Id);
          foreach (NewsCategoryLocale categoryLocale in listCategoryLocale)
          {
            categoryLocaleService.Delete(categoryLocale);
          }

          NewsCategoryService nService = new NewsCategoryService();
          Domains.NewsCategory category = nService.GetById(Id);
          nService.Delete(Id);
          ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        WriteLog("NewsCategory.aspx::Delete Category", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string CreateCategory(string Name, string Description)
    {
      try
      {
        NewsCategoryLocaleService service = new NewsCategoryLocaleService();
        NewsCategory cate = new NewsCategory();
        cate.Name = Utils.SafeString(Name);
        cate.Type = NewsType;
        cate.Code = VietnameseString.Convert(Name);
        cate.CreatedBy = CurrentUser.Fullname;
        cate.CreatedDate = DateTime.Now;

        new NewsCategoryService().Save(cate);

        TList<Language> langList = new LanguageService().GetAll();
        foreach (Language lang in langList)
        {
          NewsCategoryLocale locale = new NewsCategoryLocale();
          locale.NewsCategoryId = cate.Id;
          locale.LanguageId = lang.Id;
          locale.Name = Name;
          locale.Description = Description;
          service.Save(locale);
        }
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog("NewsCategory.aspx::Create new Category", ex);
        return Resources.Messages.ERR0004;
      }
    }

    private void LoadPage()
    {
      xdsLanguage.DataFile = XmlStatusFile;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      InitPage();
      if (!IsPostBack && !IsCallback)
      {
        LoadCategory();
        LoadPage();
      }
    }

    private string LoadContent()
    {
      int languageId = -1;
      if (cbxLanguage.Value != null)
      {
        int.TryParse(cbxLanguage.Value.ToString(), out languageId);
      }
      int categoryId = -1;
      if (!string.IsNullOrEmpty(hfCategoryId.Value))
      {
        int.TryParse(hfCategoryId.Value, out categoryId);
      }
      TList<NewsCategoryLocale> listCategoryLocale = new NewsCategoryLocaleService().Find(string.Format("NewsCategoryId = {0} AND LanguageId = {1}", categoryId.ToString(), languageId.ToString()));
      if (listCategoryLocale != null && listCategoryLocale.Count > 0)
      {
        NewsCategoryLocale categoryLocale = listCategoryLocale[0];
        return string.Format("{0}|{1}", categoryLocale.Name, categoryLocale.Description);
      }
      return string.Empty;

    }
    private string SaveLocale()
    {
      try
      {
        int languageId = -1;
        if (cbxLanguage.Value != null)
        {
          int.TryParse(cbxLanguage.Value.ToString(), out languageId);
        }
        int categoryId = -1;
        if (!string.IsNullOrEmpty(hfCategoryId.Value))
        {
          int.TryParse(hfCategoryId.Value, out categoryId);
        }
        TList<NewsCategoryLocale> listCategoryLocale = new NewsCategoryLocaleService().Find(string.Format("NewsCategoryId = {0} AND LanguageId = {1}", categoryId.ToString(), languageId.ToString()));
        NewsCategoryLocale categoryLocale = null;
        if (listCategoryLocale != null && listCategoryLocale.Count > 0)
        {
          categoryLocale = listCategoryLocale[0];
        }
        else
        {
          categoryLocale = new NewsCategoryLocale();
        }
        categoryLocale.LanguageId = languageId;
        categoryLocale.NewsCategoryId = categoryId;
        categoryLocale.Name = txtName.Text.Trim();
        categoryLocale.Description = mmNote.Text.Trim();
        new NewsCategoryLocaleService().Save(categoryLocale);
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog("NewsCategory.aspx::SaveLocale", ex);
        return Resources.Messages.ERR0004;
      }
    }
    private string SaveCategory(int categoryId, string name)
    {
      try
      {
        NewsCategoryService service = new NewsCategoryService();
        Domains.NewsCategory category = null;
        if (categoryId > 0)
        {
          category = service.GetById(categoryId);
          if (category == null)
          {
            return Resources.Messages.ERR0003;
          }
        }
        else
        {
          category = new NewsCategory();
          category.Type = NewsType;
          category.CreatedBy = CurrentUser.Username;
          category.CreatedDate = DateTime.Now;
        }
        category.Name = name;
        category.Code = VietnameseString.Convert(name);

        service.Save(category);
      }
      catch (Exception ex)
      {
        WriteLog("NewsCategory.aspx::Save Category", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    #endregion

   

    #region Event

    protected void cbxLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
      LoadCategory();
    }

    protected void gvCategory_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
          
    }
    protected void gvCategory_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }
    protected void gvCategory_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteCategory(id);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadCategory();
    }
    protected void gvCategory_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      ASPxGridView gridControl = sender as ASPxGridView;
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;

      if (string.IsNullOrEmpty(name))
      {
        m_innerError = string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      else
      {
        m_innerError = SaveCategory(id, name);
      }
      e.Cancel = true;

      gridControl.CancelEdit();
      LoadCategory();
    }
    protected void gvCategory_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;
      if (string.IsNullOrEmpty(name))
      {
        m_innerError = string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      else
      {
        m_innerError = SaveCategory(-1, name);
      }

      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadCategory();
    }
    protected void gvCategory_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
    {
      if (e.Button.ButtonType == ColumnCommandButtonType.New)
        if (!CanModify) e.Visible = false;
      if (e.Button.ButtonType == ColumnCommandButtonType.Delete)
        if (!CanDelete) e.Visible = false;

      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.New)
      {
        e.Visible = false;
      }
      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.Edit)
      {
        e.Visible = false;
      }
    }
    protected void gvCategory_DataBound(object sender, EventArgs e)
    {
      if (!CanModify)
      {
        (gvCategory.Columns["Command"] as DevExpress.Web.ASPxGridView.GridViewCommandColumn).NewButton.Visible = false;
        (gvCategory.Columns["Locale"] as DevExpress.Web.ASPxGridView.GridViewColumn).Visible = false;
      }
    }

    protected void cbxCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "Load")
      {
        e.Result = string.Format("S|{0}", LoadContent());
      }
      else if (para[0] == "Save")
      {
        e.Result = SaveLocale();
      }
    }

   
    #endregion

  


  }
}
